package com.eteng.demo.util;

import java.net.ConnectException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;

import com.eteng.entity.FtpConfig;

public class FtpHelper {

	private static FtpHelper ftpHelper = new FtpHelper();
	
	private FtpHelper (){};
	
	public static FtpHelper getInstance () {
		return ftpHelper;
	}
	
	/**
	 * 获取FTP端
	 * 
	 * @param config
	 * @return
	 */
	public FTPClient getClient(FtpConfig config) {
		System.out.println("连接FTP服务器...");
		FTPClient ftpClient = null;
		try {
			ftpClient = new FTPClient();
			ftpClient.connect(config.getFtpFromHost());
			ftpClient.login(config.getFtpFromUser(), config.getFtpFromPassword());
			if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
				System.out.println("未能连接FTP，用户名或密码错误");
				ftpClient.disconnect();
			} else {
				System.out.println("FTP连接成功！！");
				ftpClient.setControlEncoding("gb2312");
				ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
				ftpClient.enterLocalPassiveMode();
			}

		} catch (Exception e) {
			if(e instanceof ConnectException){
				System.out.println("连接超时，请查看网络状况！");
			} else {
				e.printStackTrace();
			}
			
		}

		return ftpClient;
	}
	
	/**
	 * 集团FTP连接
	 * @param config
	 * @return
	 */
	public FTPClient getUpLoadClient(FtpConfig config){
		System.out.println("连接FTP服务器...准备上传");
		FTPClient ftpClient = null;
		try {
			ftpClient = new FTPClient();
			ftpClient.connect(config.getFtpToHost());
			ftpClient.login(config.getFtpToUser(), config.getFtpToPassword());
			if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
				System.out.println("未能连接FTP，用户名或密码错误");
				ftpClient.disconnect();
			} else {
				System.out.println("集团FTP连接成功！！");
				ftpClient.setControlEncoding("gb2312");
				ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
				FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); 
				conf.setServerLanguageCode("zh"); 
				ftpClient.configure(conf);
				ftpClient.enterLocalPassiveMode();
			}

		} catch (Exception e) {
			if(e instanceof ConnectException){
				System.out.println("连接超时，请查看网络状况！");
			} else {
				e.printStackTrace();
			}
			
		}

		return ftpClient;
	}

}
